<template>
  <div class="popup-content">
    <!-- 我的频道 -->
    <van-cell center :border="false">
      <template #title>
        <span class="title-text">我的频道</span>
      </template>
      <van-button class="edit-btn" type="danger" @click="isEdit = !isEdit" plain round size="mini">
        {{ isEdit ? '完成' : '编辑' }}</van-button>
    </van-cell>
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item v-for="(channel, index) in myChannels" :key="index" class="grid-item"
        @click="OnMyChannel(channel, index)">
        <!-- 删除的小图标 -->
        <template #icon>
          <van-icon v-show="isEdit && !dataList.felxChannels.includes(channel.id)" name="clear" />
        </template>
        <!-- 我的频道内容 -->
        <template #text>
          <span class="text" :class="active === index ? 'active' : ''">{{ channel.name }}</span>
        </template>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell center :border="false">
      <template #title>
        <span class="title-text">频道推荐</span>
      </template>
    </van-cell>
    <van-grid class="recommend-grid" :gutter="10">
      <van-grid-item icon="plus" class="grid-item" v-for="resChannel in dataList.residueTabs" :key="resChannel.id"
        :text="resChannel.name" @click="OnAddChannel(resChannel)" />
    </van-grid>
  </div>
</template>

<script>
import { getAllHomeTabAPI, addUserChannelAPI, delUserChannelAPI } from '@/api/user'
import { onMounted, reactive, watch, ref, computed, toRaw } from 'vue'
import { useStore } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'popupContent',
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  setup (props, content) {
    const dataList = reactive({
      allTab: [],
      residueTabs: [],
      felxChannels: [0]// 固定频道 我的频道中不可删除
    })
    const store = useStore()
    const user = computed(() => toRaw(store.state.user))
    const myChannels = ref(props.myChannels)
    const isEdit = ref(false)// 控制我的频道中编辑状态
    // 获取所有频道数据
    const getAllHomeTab = async () => {
      try {
        const { data } = await getAllHomeTabAPI()
        dataList.allTab = data.data.channels
      } catch (err) {
        console.log('获取失败')
      }
    }
    // 往我的频道中添加推荐频道
    const OnAddChannel = async (resChannel) => {
      myChannels.value.push(resChannel)
      if (user.value) {
        // 已经登录 调用接口缓存到数据库
        try {
          await addUserChannelAPI({
            id: resChannel.id,
            seq: myChannels.value.length
          })
        } catch (err) {
          console.log(err)
        }
      } else {
        // 未登录添加到数据持久化
        setItem('TOUDIAO_NAMELIST', myChannels.value)
      }
    }
    // 删除持久化
    const deleteChannel = async (channel) => {
      if (user.value) {
        try {
          await delUserChannelAPI(channel.id)
        } catch (err) {
          console.log(err)
        }
      } else {
        // 未登录添加到数据持久化
        setItem('TOUDIAO_NAMELIST', myChannels.value)
      }
    }
    // 我的频道中的点击事件，编辑中是删除我的频道，非编辑中是跳转到对应Home的页面
    const OnMyChannel = (channel, index) => {
      // 编辑状态
      if (isEdit.value) {
        // 固定栏目不删 返回空
        if (dataList.felxChannels.includes(index)) {
          return
        }
        // 删除所选前面的项时，active也跟随减一
        if (index < props.active) {
          console.log(props.active - 1)
          content.emit('UpdateActive', props.active - 1, true)
        }
        myChannels.value.splice(index, 1)
        console.log('1')
        // 删除持久化
        deleteChannel(channel)
      } else {
        // 非编辑状态 实现切换频道
        content.emit('UpdateActive', index, false)
      }
    }
    setTimeout(() => {
      // 获取推荐列表
      watch(myChannels.value, (newValue, oldValue) => {
        //  console.log("1")
        const channels = []
        // 遍历总的allchannels
        dataList.allTab.forEach(channel => {
          // 在mychanlles中对比总的allchannels，看有无一样的
          const ret = myChannels.value.find(myChannel => {
            return myChannel.id === channel.id
          })
          // 没有一样的则添加到推荐列表中
          if (!ret) {
            channels.push(channel)
          }
        })
        dataList.residueTabs = channels
      }, { immediate: true })
    }, 500)

    onMounted(() => {
      getAllHomeTab()
    })
    return {
      dataList,
      OnAddChannel,
      isEdit,
      OnMyChannel
    }
  }
}
</script>

<style scoped lang="less">
.popup-content {
  padding: 85px 0;

  .title-text {
    font-size: 32px;
    color: #333333;
  }

  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }

  :deep(.grid-item) {
    width: 160px;
    height: 86px;

    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;

      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }

      .active {
        color: red;
      }
    }

    .van-badge__wrapper {
      position: unset;
    }
  }

  :deep(.my-grid) {
    .van-icon-clear {
      position: absolute;
      right: -10px;
      top: -10px;
      font-size: 30px;
      color: #cacaca;
      z-index: 2;
    }
  }

  :deep(.recommend-grid) {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;

        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>
